//
//  BMSToastManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSToastManager.h"

@interface BMSToastManager()


@end

@implementation BMSToastManager

+ (void)showToast:(NSString *)message {
    [self showToast:message duration:2.0 inView:nil position:CGPointZero];
}

+ (void)showToast:(NSString *)message
         duration:(NSTimeInterval)duration
           inView:(UIView *)view
         position:(CGPoint)center
{
    if (message.length == 0) return;

    UIView *container = view ?: UIApplication.sharedApplication.keyWindow;
    if (!container) return;

    UILabel *toastLabel = [[UILabel alloc] init];
    toastLabel.text = message;
    toastLabel.textColor = [UIColor whiteColor];
    toastLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.75];
    toastLabel.textAlignment = NSTextAlignmentCenter;
    toastLabel.font = [UIFont systemFontOfSize:14];
    toastLabel.numberOfLines = 0;
    toastLabel.layer.cornerRadius = 8;
    toastLabel.clipsToBounds = YES;

    CGSize maxSize = CGSizeMake(container.bounds.size.width - 40, CGFLOAT_MAX);
    CGSize textSize = [toastLabel sizeThatFits:maxSize];
    toastLabel.frame = CGRectMake(0, 0, textSize.width + 20, textSize.height + 20);

    if (CGPointEqualToPoint(center, CGPointZero)) {
        center = CGPointMake(CGRectGetMidX(container.bounds), CGRectGetMidY(container.bounds));
    }
    toastLabel.center = center;

    toastLabel.alpha = 0.0;
    [container addSubview:toastLabel];

    [UIView animateWithDuration:0.25 animations:^{
        toastLabel.alpha = 1.0;
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.25 animations:^{
            toastLabel.alpha = 0.0;
        } completion:^(BOOL finished) {
            [toastLabel removeFromSuperview];
        }];
    });
}

@end
